<template>
  <div class="dashboard">
    <el-row class="mb-4">
      <el-col :span="24">
        <h2 class="dashboard-title">系统概览</h2>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="quick-stats">
      <el-col :span="6" v-for="(stat, index) in statsData" :key="index">
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
          <template #header>
            <div class="stat-header">
              <el-icon :size="20" :color="stat.color">
                <component :is="stat.icon" />
              </el-icon>
              <span>{{ stat.title }}</span>
            </div>
          </template>
          <div class="stat-value">{{ stat.value }}</div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row class="quick-actions">
      <el-col :span="24">
        <h3 class="section-title">快捷操作</h3>
        <div class="action-grid">
          <el-button
            v-for="(action, index) in quickActions"
            :key="index"
            type="primary"
            size="large"
            class="action-button"
            @click="action.handler"
          >
            <el-icon class="action-icon">
              <component :is="action.icon" />
            </el-icon>
            <span>{{ action.name }}</span>
          </el-button>
        </div>
      </el-col>
    </el-row>
  </div>

  <!-- 添加图书对话框 -->
  <el-dialog
    v-model="bookDialog.visible"
    title="图书入库"
    width="50%"
  >
    <el-form
      ref="bookFormRef"
      :model="bookForm"
      :rules="bookRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="cover-section">
            <div class="section-title">图书封面</div>
            <el-upload
              class="book-cover-uploader"
              :show-file-list="false"
              :before-upload="beforeCoverUpload"
              :http-request="handleCoverSuccess"
            >
              <div class="cover-preview">
                <img
                  v-if="bookForm.cover"
                  :src="bookForm.cover"
                  class="book-cover"
                />
                <div v-else class="upload-placeholder">
                  <el-icon class="book-cover-uploader-icon"><Plus /></el-icon>
                  <span>上传封面</span>
                </div>
              </div>
            </el-upload>
            <div class="upload-tip">
              建议尺寸: 350x500px<br/>
              支持 jpg、png 格式
            </div>
          </div>
        </el-col>
        <el-col :span="16">
          <el-form-item label="所属分类" prop="category_id">
            <el-cascader
              v-model="bookForm.category_id"
              :options="categories"
              :props="{ checkStrictly: true, value: 'id', label: 'label', children: 'children' }"
              clearable
              placeholder="请选择图书分类"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="书名" prop="title">
            <el-input v-model="bookForm.title" />
          </el-form-item>
          <el-form-item label="作者" prop="author">
            <el-input v-model="bookForm.author" />
          </el-form-item>
          <el-form-item label="ISBN" prop="isbn">
            <el-input v-model="bookForm.isbn">
              <template #append>
                <el-button :icon="Camera" @click="openScanner" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="出版社" prop="publisher">
            <el-input v-model="bookForm.publisher" />
          </el-form-item>
          <el-form-item label="出版日期" prop="publish_date">
            <el-date-picker
              v-model="bookForm.publish_date"
              type="date"
              placeholder="选择出版日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="图书总数" prop="total_copies">
            <el-input-number
              v-model="bookForm.total_copies"
              :min="1"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="馆藏位置" prop="location">
            <el-input v-model="bookForm.location" />
          </el-form-item>
          <el-form-item label="图书简介" prop="description">
            <el-input
              v-model="bookForm.description"
              type="textarea"
              :rows="4"
              :maxlength="500"
              show-word-limit
              placeholder="请输入图书简介（最多500字）"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="bookDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveBook">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 扫码对话框 -->
  <el-dialog
    v-model="scannerDialog.visible"
    title="扫描ISBN"
    width="400px"
    destroy-on-close
  >
    <steam-barcode-reader
      @decode="handleScanResult"
      style="width: 100%; height: 300px"
    />
  </el-dialog>

  <!-- 借阅登记对话框 -->
  <el-dialog
    v-model="borrowDialog.visible"
    :title="borrowDialog.title"
    width="60%"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <!-- 扫描借阅证阶段 -->
    <div v-if="!currentReader" class="scan-reader">
      <div v-if="!startScanning" class="start-scan-button">
        <el-button type="primary" size="large" @click="startScanningReader">
          <el-icon><VideoCameraFilled /></el-icon>
          开始扫描借阅证
        </el-button>
      </div>
      <div v-else class="scan-area">
        <steam-barcode-reader @decode="handleReaderScan" :paused="!startScanning" />
        <el-button class="cancel-scan" @click="cancelScanningReader">取消扫描</el-button>
      </div>
    </div>

    <!-- 扫描图书阶段 -->
    <div v-else class="borrow-content">
      <!-- 读者信息 -->
      <el-card class="reader-info-card">
        <div class="reader-info">
          <div><label>姓名：</label>{{ currentReader.name }}</div>
          <div><label>学号：</label>{{ currentReader.studentId }}</div>
          <div><label>已借：</label>{{ currentReader.books.length }}/{{ maxBorrow }}本</div>
        </div>
      </el-card>

      <!-- 扫描区域 -->
      <div class="scan-book-area">
        <steam-barcode-reader
          v-if="isBookScanning"
          @decode="handleBookScan"
          :paused="!isBookScanning"
        />
        <el-button
          v-else
          type="primary"
          @click="startBookScan"
        >开始扫描图书</el-button>
      </div>

      <!-- 已扫描图书列表 -->
      <div class="scanned-books">
        <h4>待{{ borrowDialog.type === 'borrow' ? '借阅' : '归还' }}图书</h4>
        <el-table :data="scannedBooks" style="width: 100%">
          <el-table-column prop="title" label="书名" />
          <el-table-column prop="author" label="作者" width="120" />
          <el-table-column prop="location" label="位置" width="120" />
          <el-table-column
            v-if="borrowDialog.type === 'return'"
            prop="status"
            label="状态"
            width="100"
          >
            <template>
              <el-tag type="warning">待归还</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template #default="scope">
              <el-button
                type="danger"
                :icon="Delete"
                circle
                @click="removeBook(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button
          v-if="currentReader && scannedBooks.length > 0"
          type="primary"
          @click="handleConfirmOperation"
        >
          确认{{ borrowDialog.type === 'borrow' ? '借阅' : '归还' }}
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 添加学生信息对话框 -->
  <el-dialog
    v-model="readerDialog.visible"
    title="添加学生"
    width="60%"
    :close-on-click-modal="false"
  >
    <el-form
      :model="readerForm"
      :rules="readerRules"
      ref="readerFormRef"
      label-width="100px"
      class="reader-form"
    >
      <!-- 添加照片上传部分 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="证件照片" prop="photo">
            <div class="upload-container">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforePhotoUpload"
                :http-request="handlePhotoUpload"
              >
                <img v-if="readerForm.student_img" :src="readerForm.student_img" class="avatar" />
                <div v-else class="avatar-placeholder">
                  <el-icon><Plus /></el-icon>
                  <span>上传照片</span>
                </div>
              </el-upload>
              <div class="upload-tip">
                <p>请上传证件照片，要求：</p>
                <p>1. 图片格式：JPG、PNG</p>
                <p>2. 图片大小：不超过2MB</p>
                <p>3. 比例：3:4 建议尺寸：300x400px</p>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="学号" prop="studentno">
            <el-input v-model="readerForm.studentno" placeholder="请输入学号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="账号" prop="username">
            <el-input v-model="readerForm.username" placeholder="请输入账号名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入学年份" prop="Yearofadmission">
            <el-date-picker
              v-model="readerForm.Yearofadmission"
              type="year"
              placeholder="请选择入学年份"
              format="YYYY"
              value-format="YYYY"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学院" prop="collegeAndMajor">
            <el-cascader
              v-model="readerForm.collegeAndMajor"
              :options="collegeOptions"
              :props="{
                value: 'value',
                label: 'label',
                children: 'children',
              }"
              @change="handleCollegeChange"
              placeholder="请选择学院和专业方向"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="班级" prop="class">
            <el-input v-model="readerForm.class" placeholder="请输入班级" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="real_name">
            <el-input v-model="readerForm.real_name" placeholder="请输入真实姓名" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="readerDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleAddReader">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { 
  Reading, 
  User, 
  Box, 
  TrendCharts,
  Plus,
  Download,
  Upload,
  UserFilled,
  Camera,
  Delete, 
  VideoCameraFilled 
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  uploadBookCover, 
  addNewBook, 
  getAllBookCategory,
  getUserBorrowInfoByCardno, 
  getBookInfoByISBN, 
  borrowBook, 
  returnBook,
  getAllCollegeAndMajors,
  uploadPhoto,
  addNewStudent,
  getCurrentLibData
} from '@/api/index';
import SteamBarcodeReader from "@/components/steambarcodereader.vue";

// 统计数据
const statsData = ref([
  { title: '馆藏总量', value: '0', icon: 'Reading', color: '#409EFF' },
  { title: '借阅人数', value: '0', icon: 'User', color: '#67C23A' },
  { title: '今日借出', value: '0', icon: 'Box', color: '#E6A23C' },
  { title: '待归还', value: '0', icon: 'TrendCharts', color: '#F56C6C' }
]);

// 获取统计数据
const getLibraryStats = async () => {
  try {
    const response = await getCurrentLibData();
    if (response.code === 200) {
      statsData.value = [
        { title: '馆藏总量', value: response.data.book_total, icon: 'Reading', color: '#409EFF' },
        { title: '借阅人数', value: response.data.user_total, icon: 'User', color: '#67C23A' },
        { title: '今日借出', value: response.data.borrow_today, icon: 'Box', color: '#E6A23C' },
        { title: '待归还', value: response.data.borrowing_total, icon: 'TrendCharts', color: '#F56C6C' }
      ];
    } else {
      ElMessage.error('获取统计数据失败');
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    ElMessage.error('获取统计数据失败');
  }
};

// 在onMounted中调用获取数据
onMounted(() => {
  getLibraryStats();
});

// 快捷操作
const quickActions = ref([
  { 
    name: '图书入库', 
    icon: Plus, 
    handler: async () => {
      // 确保有分类数据
      if (categories.value.length === 0) {
        await getBookCategory();
      }
      bookDialog.value.visible = true;
      bookDialog.value.type = "add";
      bookForm.value = {
        title: "",
        author: "",
        isbn: "",
        publisher: "",
        publish_date: "",
        location: "",
        cover: "",
        category_id: null,
        total_copies: 1,
        borrow_copies: 0,
        description: "",
        book_status: 0
      };
    }
  },
  { 
    name: '借书登记', 
    icon: Download, 
    handler: () => {
      borrowDialog.value = {
        visible: true,
        type: 'borrow',
        title: '借书登记'
      };
    }
  },
  { 
    name: '还书登记', 
    icon: Upload, 
    handler: () => {
      borrowDialog.value = {
        visible: true,
        type: 'return',
        title: '还书登记'
      };
    }
  },
  { 
    name: '学生登记', 
    icon: UserFilled, 
    handler: async () => {
      await getCollegeWithMajorsData();
      readerDialog.value.visible = true;
    } 
  }
]);

// 添加图书相关的响应式数据
const bookDialog = ref({
  visible: false,
  type: "add",
});

const bookForm = ref({
  title: "",
  author: "",
  isbn: "",
  publisher: "",
  publish_date: "",
  location: "",
  cover: "",
  category_id: null,
  total_copies: 1,
  borrow_copies: 0,
  description: "",
  book_status: 0
});

const bookFormRef = ref(null);
const categories = ref([]);

// 图书表单验证规则
const bookRules = {
  title: [
    { required: true, message: "请输入书名", trigger: "blur" },
    { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" },
  ],
  author: [{ required: true, message: "请输入作者", trigger: "blur" }],
  isbn: [{ required: true, message: "请输入ISBN", trigger: "blur" }],
  publisher: [{ required: true, message: "请输入出版社", trigger: "blur" }],
  publish_date: [{ required: true, message: "请选择出版日期", trigger: "change" }],
  total_copies: [
    { required: true, message: "请输入图书总数量", trigger: "blur" },
    { type: 'number', min: 1, message: "数量必须大于0", trigger: "blur" }
  ],
  category_id: [{ required: true, message: "请选择图书分类", trigger: "change" }],
};

// 添加获取图书分类的方法
const getBookCategory = async () => {
  try {
    const response = await getAllBookCategory();
    categories.value = transformToTree(response.data);
  } catch (error) {
    console.error("获取图书分类失败", error);
    ElMessage.error("获取图书分类失败");
  }
};

// 添加处理图书保存的方法
const handleSaveBook = async () => {
  await bookFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          ...bookForm.value,
          category_id: Array.isArray(bookForm.value.category_id) 
            ? bookForm.value.category_id[bookForm.value.category_id.length - 1] 
            : bookForm.value.category_id,
        };

        const response = await addNewBook(submitData);
        if (response.code === 200) {
          ElMessage.success('图书添加成功');
          bookDialog.value.visible = false;
        } else {
          throw new Error(response.message || '添加失败');
        }
      } catch (error) {
        console.error('保存图书失败:', error);
        ElMessage.error(error.message || '保存失败，请重试');
      }
    }
  });
};

// 添加扫码相关功能
const scannerDialog = ref({
  visible: false,
});

const handleScanResult = (result) => {
  bookForm.value.isbn = result;
  scannerDialog.value.visible = false;
  ElMessage.success(`扫描成功：${result}`);
};

const openScanner = () => {
  scannerDialog.value.visible = true;
};

// 添加封面上传相关方法
const beforeCoverUpload = (file) => {
  const fileExt = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
  const isValidType = ['.jpg', '.jpeg', '.png'].includes(fileExt);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isValidType) {
    ElMessage.error('只支持JPG、JPEG和PNG格式的图片！');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过2MB！');
    return false;
  }
  return true;
};

const handleCoverSuccess = async (params) => {
  try {
    const formData = new FormData();
    formData.append('file', params.file);
    
    const response = await uploadBookCover(formData);
    if (response.code === 200) {
      bookForm.value.cover = response.data;
      ElMessage.success('封面上传成功');
    } else {
      throw new Error(response.message || '上传失败');
    }
  } catch (error) {
    console.error('封面上传失败:', error);
    ElMessage.error(error.message || '封面上传失败，请重试');
  }
};

// 添加用于转换分类数据为树形结构的方法
const transformToTree = (flatData) => {
  const map = {};
  const tree = [];

  flatData.forEach((item) => {
    map[item.category_id] = {
      ...item,
      id: item.category_id,
      label: item.category_name,
      children: [],
    };
  });

  flatData.forEach((item) => {
    const node = map[item.category_id];
    if (item.parent_id === 0) {
      tree.push(node);
    } else {
      const parent = map[item.parent_id];
      if (parent) {
        parent.children.push(node);
        parent.children.sort((a, b) => a.sort_order - b.sort_order);
      }
    }
  });

  tree.sort((a, b) => a.sort_order - b.sort_order);
  return tree;
};

// 借阅相关的响应式数据
const borrowDialog = ref({
  visible: false,
  type: '',
  title: ''
});

const currentReader = ref(null);
const startScanning = ref(false);
const isBookScanning = ref(false);
const scannedBooks = ref([]);
const maxBorrow = 5;
const readerCard = ref(null);

// 处理读者证扫描
const handleReaderScan = async (result) => {
  try {
    const cardno = result;
    readerCard.value = { cardno };
    const response = await getUserBorrowInfoByCardno(readerCard.value);
    if (response.code === 200) {
      currentReader.value = {
        id: response.data.user_id,
        name: response.data.real_name,
        studentId: response.data.studentno,
        books: response.data.borrowingBooks || []
      };
      startScanning.value = false;
      ElMessage.success(`欢迎，${currentReader.value.name}`);
    } else {
      ElMessage.error(response.msg || '读者信息获取失败');
    }
  } catch (error) {
    console.error('获取读者信息错误:', error);
    ElMessage.error('读者信息获取失败');
  }
};

// 处理图书扫描
const handleBookScan = async (result) => {
  try {
    if (scannedBooks.value.some(book => book.isbn === result)) {
      ElMessage.warning('该图书已扫描');
      return;
    }

    const params = {
      isbn: result,
      operation: borrowDialog.value.type,
      user_id: currentReader.value.id
    };

    const response = await getBookInfoByISBN(params);
    
    if (response.code === 200) {
      if (borrowDialog.value.type === 'borrow' && currentReader.value.books.length >= maxBorrow) {
        ElMessage.warning('已达最大借阅数量');
        return;
      }
      
      const bookInfo = {
        title: response.data.title,
        author: response.data.author,
        location: response.data.location,
        book_id: response.data.book_id,
        isbn: result
      };
      
      scannedBooks.value.push(bookInfo);
      ElMessage.success(`成功扫描：${bookInfo.title}`);
    } else {
      ElMessage.error(response.msg || '图书信息获取失败');
    }
  } catch (error) {
    console.error('获取图书信息错误:', error);
    ElMessage.error('图书信息获取失败');
  }
};

// 开始扫描
const startScanningReader = () => {
  startScanning.value = true;
};

const startBookScan = () => {
  isBookScanning.value = true;
};

// 取消扫描
const cancelScanningReader = () => {
  startScanning.value = false;
};

// 移除已扫描的书籍
const removeBook = (index) => {
  scannedBooks.value.splice(index, 1);
};

// 确认操作
const handleConfirmOperation = async () => {
  try {
    const operationType = borrowDialog.value.type === 'borrow' ? '借阅' : '归还';
    const confirmResult = await ElMessageBox.confirm(
      `确认${operationType}这些图书吗？`,
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    if (confirmResult === 'confirm') {
      const params = {
        user_id: currentReader.value.id,
        books: scannedBooks.value.map(book => book.book_id)
      };

      const response = await (borrowDialog.value.type === 'borrow' 
        ? borrowBook(params) 
        : returnBook(params));

      if (response.code === 200) {
        ElMessage.success(`${operationType}成功`);
        borrowDialog.value.visible = false;
        resetBorrowDialog();
      } else {
        ElMessage.error(response.msg || `${operationType}失败`);
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error);
      ElMessage.error('操作失败，请重试');
    }
  }
};

// 关闭对话框
const handleDialogClose = () => {
  ElMessageBox.confirm(
    '确认关闭吗？未保存的操作将会丢失',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      borrowDialog.value.visible = false;
      resetBorrowDialog();
    })
    .catch(() => {});
};

// 重置对话框状态
const resetBorrowDialog = () => {
  currentReader.value = null;
  startScanning.value = false;
  isBookScanning.value = false;
  scannedBooks.value = [];
  readerCard.value = null;
};

// 添加学生相关数据
const readerDialog = ref({
  visible: false
});

const readerForm = ref({
  student_img: "",
  studentno: "",
  username: "",
  real_name: "",
  college: "",
  classes: "",
  major: "",
  Yearofadmission: "",
  collegeAndMajor: [],
  photoFile: null,
  college_id: "",
});

const readerFormRef = ref(null);

const readerRules = {
  studentno: [
    { required: true, message: "请输入学号", trigger: "blur" },
    { min: 8, max: 12, message: "学号长度在8到12个字符之间", trigger: "blur" },
    { pattern: /^\d+$/, message: "学号只能包含数字", trigger: "blur" }
  ],
  username: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 4, max: 20, message: "账号长度在4到20个字符之间", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9_]+$/, message: "账号只能包含字母、数字和下划线", trigger: "blur" }
  ],
  real_name: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度在2到20个字符之间", trigger: "blur" },
    { pattern: /^[\u4e00-\u9fa5]{2,20}$/, message: "姓名只能输入中文", trigger: "blur" }
  ],
  collegeAndMajor: [
    {
      required: true,
      message: "请选择学院和专业方向",
      trigger: "change"
    }
  ],
  class: [{ required: true, message: "请输入班级", trigger: "blur" }],
  Yearofadmission: [
    { required: true, message: "请选择入学年份", trigger: "change" }
  ],
};

// 学院和专业数据
const collegeData = ref([]);
const collegeOptions = computed(() => {
  const groupedData = collegeData.value.reduce((acc, curr) => {
    if (!acc[curr.college_name]) {
      acc[curr.college_name] = {
        college_name: curr.college_name,
        majors: []
      };
    }
    acc[curr.college_name].majors.push({
      professional: curr.professional,
      college_id: curr.college_id
    });
    return acc;
  }, {});

  return Object.values(groupedData).map(college => ({
    value: college.college_name,
    label: college.college_name,
    children: college.majors.map(major => ({
      value: major.college_id,
      label: major.professional,
    }))
  }));
});

// 获取院系和专业数据
const getCollegeWithMajorsData = async () => {
  try {
    const res = await getAllCollegeAndMajors();
    if (res && res.code === 200) {
      collegeData.value = res.data;
    } else {
      ElMessage.error("获取院系和专业数据失败");
    }
  } catch (error) {
    console.error("请求失败:", error);
    ElMessage.error("获取院系和专业数据失败");
  }
};

// 处理级联选择器改变事件
const handleCollegeChange = (value) => {
  if (value && value.length === 2) {
    const college_name = value[0];
    const college_id = value[1];
    
    const majorInfo = collegeData.value.find(item => item.college_id === college_id);
    
    if (majorInfo) {
      readerForm.value.college_id = college_id;
      readerForm.value.college = college_name;
      readerForm.value.major = majorInfo.professional;
    }
  } else {
    readerForm.value.college_id = '';
    readerForm.value.college = '';
    readerForm.value.major = '';
  }
};

// 照片上传相关方法
const beforePhotoUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('只能上传 JPG 或 PNG 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handlePhotoUpload = async (params) => {
  const file = params.file
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const res = await uploadPhoto(formData)
    if (res.code === 200) {
      readerForm.value.photoFile = file;
      readerForm.value.student_img = res.data;
      ElMessage.success('照片上传成功');
    } else {
      ElMessage.error(res.msg || '照片上传失败');
    }
  } catch (error) {
    console.error('照片上传失败:', error);
    ElMessage.error('照片上传失败');
  }
}

// 处理添加学生
const handleAddReader = async () => {
  if (!readerFormRef.value) return;
  
  await readerFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          student_img: readerForm.value.student_img,
          studentno: readerForm.value.studentno,
          username: readerForm.value.username,
          real_name: readerForm.value.real_name,
          college_id: readerForm.value.college_id,
          college: readerForm.value.college,
          classes: readerForm.value.class,
          professional: readerForm.value.major,
          yearofadmission: readerForm.value.Yearofadmission
        };

        const res = await addNewStudent(submitData);
        
        if (res.code === 200) {
          ElMessage.success('添加学生成功');
          readerDialog.value.visible = false;
          readerFormRef.value.resetFields();
          readerForm.value.student_img = '';
          readerForm.value.photoFile = null;
        } else {
          ElMessage.error(res.msg || '添加学生失败');
        }
      } catch (error) {
        console.error('添加学生失败:', error);
        ElMessage.error('添加学生失败');
      }
    }
  });
};

</script>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
}

.dashboard-title {
  margin: 0 0 20px;
  font-size: 22px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.section-title {
  margin: 0 0 20px;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.quick-stats {
  margin-bottom: 30px;
  display: flex;
  flex-wrap: wrap;
}

.quick-stats .el-col {
  margin-bottom: 20px;
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--el-text-color-regular);
  padding: 10px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: var(--el-color-primary);
  text-align: center;
  padding: 20px 0;
}

.quick-actions {
  margin-top: 30px;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.action-button {
  width: 100%;
  height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 16px;
}

.action-icon {
  font-size: 24px;
}

.mb-4 {
  margin-bottom: 16px;
}

/* 添加图书封面上传相关样式 */
.cover-section {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.section-title {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-bottom: 16px;
  align-self: flex-start;
}

.cover-preview {
  width: 180px;
  height: 260px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--el-fill-color-lighter);
  border-radius: 6px;
  overflow: hidden;
}

.book-cover-uploader {
  width: 180px;
}

.book-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: var(--el-text-color-secondary);
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  text-align: center;
}

.book-cover-uploader-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.scan-reader {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.scan-area {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f5f7fa;
  border-radius: 4px;
}

.reader-info-card {
  margin-bottom: 20px;
}

.reader-info {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.reader-info label {
  font-weight: bold;
  margin-right: 8px;
}

.scan-book-area {
  height: 250px;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  border-radius: 4px;
}

.scanned-books {
  margin-top: 20px;
}

.cancel-scan {
  margin-top: 10px;
}

/* 调整视频高度 */
.scan-area :deep(video),
.scan-book-area :deep(video) {
  max-height: 245px;
  object-fit: cover;
}

/* 添加学生表单相关样式 */
.upload-container {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.avatar-uploader {
  width: 180px;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-placeholder {
  width: 180px;
  height: 240px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.avatar {
  width: 180px;
  height: 240px;
  object-fit: cover;
}

.upload-tip {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  line-height: 1.5;
}

.upload-tip p {
  margin: 4px 0;
}
</style>